<?php

/**
 * AVE.cms - Модуль Навигация
 *
 * @package AVE.cms
 * @subpackage module_Navigation
 * @since 1.4
 * @filesource
 */

if (!defined('BASE_DIR')) exit;

if (defined('ACP'))
{
	$modul['ModulName'] = 'Навигация';
	$modul['ModulPfad'] = 'navigation';
	$modul['ModulVersion'] = '1.2';
	$modul['description'] = 'Данный модуль предназначен не только для создания различных видов меню (горизонтального или вертикального), но и меню навигаций, состоящих из различного количества пунктов и уровней вложенности. Помните, что максимальная глубина уровней вложенности не может быть больше 3. Для создания меню, перейдите в раздел <strong>Навигация</strong>. Для отображения меню на сайте разместите системный тег <strong>[mod_navigation:XXX]</strong> в нужном месте вашего шаблона. ХХХ - это порядковый номер меню.';
	$modul['Autor'] = 'Arcanum';
	$modul['MCopyright'] = '&copy; 2007 Overdoze Team';
	$modul['Status'] = 1;
	$modul['IstFunktion'] = 1;
    $modul['AdminEdit'] = 0;
	$modul['ModulFunktion'] = 'mod_navigation';
	$modul['CpEngineTagTpl'] = '[mod_navigation:XXX]';
	$modul['CpEngineTag'] = '#\\\[mod_navigation:(\\\d+)]#';
	$modul['CpPHPTag'] = "<?php mod_navigation(''$1''); ?>";
}

if (defined('ACP') && !(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete'))
{
	$modul_sql_update = array();
	$modul_sql_update[] = "UPDATE CPPREFIX_module SET CpEngineTag = '" . $modul['CpEngineTag'] . "', CpPHPTag = '" . $modul['CpPHPTag'] . "', Version = '" . $modul['ModulVersion'] . "' WHERE ModulPfad = '" . $modul['ModulPfad'] . "' LIMIT 1;";
}

/**
 * Функция обработки тэга модуля
 *
 * @param int $navigation_id - идентификатор меню навигации
 */
function mod_navigation($navigation_id)
{
	global $AVE_DB, $AVE_Core;

    //static $navigations = array();
    if($navigation_id == '99'){
    	$navigation_id = '1';
    	$orders = "navi_item_position DESC";
    }
    $orders = (!empty($orders)) ? $orders : "navi_item_position ASC";
    
    

	$navigation_id  = preg_replace('/\D/', '', $navigation_id);

	if (isset($navigations[$navigation_id]))
	{
		echo $navigations[$navigation_id];
		return;
	}

	$nav = get_navigations($navigation_id);
//print_r($nav);

	if (!$nav)
	{
		echo 'Menu ', $navigation_id, ' not found';
		return;
	}

	if (!defined('UGROUP')) define('UGROUP', 2);
	if (!in_array(UGROUP, $nav->navi_user_group)) return;

		$curent_doc_id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? $_GET['id'] : 1;



		$curent_gal_rub_id = (isset($_GET['galrubid']) && is_numeric($_GET['galrubid'])) ? $_GET['galrubid'] : 1;
		$curent_gal_id = (isset($_GET['galid']) && is_numeric($_GET['galid'])) ? $_GET['galid'] : 1;

#########################################
#########################################
#########для реврайтов мудулей###########
	$conect = "";
	$reqest = "";
	
if (isset($_REQUEST['module']) && $_REQUEST['module']!='' && $_REQUEST['module'] == 'articles'){

	$conect = " JOIN " . PREFIX . "_modul_articles_rubz AS artrub";
	$reqest = " AND nav.Id = artrub.document_linked_navi_id AND artrub.id = ".$_REQUEST['article'];
} 	
	
	
if (isset($_REQUEST['module']) && $_REQUEST['module']!='' && $_REQUEST['module'] == 'gallery' && $_REQUEST['action'] == 'GetCat'){

	$conect = " JOIN " . PREFIX . "_modul_gallery_rubz AS galrub";
	$reqest = " AND nav.Id = galrub.document_linked_navi_id AND galrub.id = ".$_REQUEST['rubid'];
} 		

if (isset($_REQUEST['module']) && $_REQUEST['module']!='' && $_REQUEST['module'] == 'gallery' && $_REQUEST['action'] == 'ShowGal'){

	$conect = " JOIN " . PREFIX . "_modul_gallery AS gal";
	$reqest = " AND nav.Id = gal.document_linked_navi_id AND gal.id = ".$_REQUEST['galid'];
} 	

if (isset($_REQUEST['module']) && $_REQUEST['module']!='' && $_REQUEST['module'] == 'guestbook'){

	$conect = "";
	$reqest = "AND nav.document_alias LIKE '%%/comment%%'";
} 	

/*
		@$extended_by_module = "(".$navi_item_link." LIKE '%%" . $refurl2 . "%%')";
		@$extended_by_module2 = "(nav.document_alias LIKE '%%" . $refurl2 . "%%')";
*/

///comment
	if (isset($_REQUEST['module']) && $_REQUEST['module']!='' && $_REQUEST['module'] == 'guestbook')
	{
		//$refurl = "/comment";
		//$refurl2 = "/comment";
		//$refurl3 = "/comment";
	}
	else
	{

		  $refurl = 'index.php?id=' . $curent_doc_id;
	}

	$navi_item_link = "nav.navi_item_link_".$_SESSION['user_language'];

	if (empty($_REQUEST['module']))
	{
		$row_navi = $AVE_DB->Query("
			SELECT CONCAT_WS(',', nav.Id, nav.parent_id, nav2.parent_id)
			FROM
				" . PREFIX . "_navigation_items AS nav
			JOIN
				" . PREFIX . "_documents AS doc
			LEFT JOIN
				" . PREFIX . "_navigation_items AS nav2 ON nav2.Id = nav.parent_id
			WHERE nav.navi_item_status = 1
			AND nav.navi_id = '" . $navigation_id . "'
			AND doc.Id = '" . $curent_doc_id . "'
			AND (".$navi_item_link." = 'index.php?id=" . $curent_doc_id . "'"
				. ((!empty($AVE_Core->curentdoc->document_alias) && $AVE_Core->curentdoc->Id == $curent_doc_id) ? " OR nav.document_alias = '" . $AVE_Core->curentdoc->document_alias . "'" : '')
				. " OR nav.Id = doc.document_linked_navi_id)
		")->GetCell();
	}
	else
	{
		
		@$extended_by_module = "(".$navi_item_link." LIKE '%%" . $refurl2 . "%%')";
		@$extended_by_module2 = "(nav.document_alias LIKE '%%" . $refurl2 . "%%')";

		
		$row_navi = $AVE_DB->Query("
			SELECT CONCAT_WS(',',nav.Id, nav.parent_id, nav2.parent_id)
			FROM
				" . PREFIX . "_navigation_items AS nav
			".$conect."
			LEFT JOIN
				" . PREFIX . "_navigation_items AS nav2 ON nav2.Id = nav.parent_id
			WHERE nav.navi_item_status = '1'
			$reqest
		")->GetCell();
		


		if(empty($row_navi))
		{
			$row_navi = $AVE_DB->Query("
				SELECT CONCAT_WS(',',nav.parent_id, nav2.parent_id)
				FROM
					" . PREFIX . "_navigation_items AS nav
				LEFT JOIN
					" . PREFIX . "_navigation_items AS nav2 ON nav2.Id = nav.parent_id
				WHERE nav.navi_item_status = '1'
				AND nav.navi_id = '" . $navigation_id . "'
				AND $extended_by_module2
			")->GetCell();
		}	
		/*
print_r("
				SELECT CONCAT_WS(',',nav.parent_id, nav2.parent_id)
				FROM
					" . PREFIX . "_navigation_items AS nav
				LEFT JOIN
					" . PREFIX . "_navigation_items AS nav2 ON nav2.Id = nav.parent_id
				WHERE nav.navi_item_status = '1'
				AND nav.navi_id = '" . $navigation_id . "'
				AND $extended_by_module2
			");
*/
		
	}
	$where_elter = '';
#########################################
#########################################
	
	//print_r($row_navi);
	if ($row_navi !== false)
	{
		$way = explode(',', $row_navi);
		if ($nav->navi_expand!=1) $where_elter = "AND parent_id IN(0," . $row_navi . ")";
		//$where_elter = "AND parent_id IN(0," . $row_navi . ")";
	}
	else
	{
		$way = array('');
		if ($nav->navi_expand!=1) $where_elter = "AND parent_id = 0";
	}
//document_linked_navi_id
//print_r("
//	SELECT *
//	FROM " . PREFIX . "_navigation_items
//	WHERE navi_item_status = '1'
//	AND navi_id = '" . $navigation_id . "'
//	" . $where_elter . "
//	ORDER BY ".$orders."
//");

	$nav_items = array();
	$sql = $AVE_DB->Query("
		SELECT *
		FROM " . PREFIX . "_navigation_items
		WHERE navi_item_status = '1'
		AND navi_id = '" . $navigation_id . "'
		" . $where_elter . "
		ORDER BY ".$orders."
	");

	while ($row_nav_item = $sql->FetchAssocArray())
	{
		$title = "title_".$_SESSION['user_language'];
		$navi_item_desc = "navi_item_desc_".$_SESSION['user_language'];
		$navi_item_link = "navi_item_link_".$_SESSION['user_language'];
		$row_nav_item['title'] = $row_nav_item[$title];		
		$row_nav_item['navi_item_desc'] = $row_nav_item[$navi_item_desc];
		$row_nav_item['navi_item_link'] = $row_nav_item[$navi_item_link];		
		$nav_items[$row_nav_item['parent_id']][$row_nav_item['Id']] = $row_nav_item;
	}
	//$row_nav_item['Id']
	//print_r($nav_items);

	$ebenen = array(
		1 =>  array(
			'aktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level1active),
			'inaktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level1),
		),
		2 =>  array(
			'aktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level2active),
			'inaktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level2),
		),
		3 =>  array(
			'aktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level3active),
			'inaktiv' => str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_level3),
		)
	);
//print_r($nav_items);
	
	$END = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_begin);

	printNavi($END, $ebenen, $way, $navigation_id, $nav_items, $nav);

	$END .= str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $nav->navi_end);
	$END = rewrite_link($END);		
	$END = preg_replace('/\[tag:submenu:(.*?)]/', '', $END);
	
	$END = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $END);
	$END = str_replace(array("\r\n","\n","\r"),'',$END);
	$END = str_replace(array("\n","\r"),'',$END);
/*	
	$search = array (
		$nav->navi_level1begin . $nav->navi_level1end,
		$nav->navi_level2begin . $nav->navi_level2end,
		$nav->navi_level3begin . $nav->navi_level3end,
		'</li>' . $nav->navi_level2begin . '<li',
		'</li>' . $nav->navi_level3begin . '<li',
		'</li>' . $nav->navi_level1end . '<li',
		'</li>' . $nav->navi_level2end . '<li',
		'</li>' . $nav->navi_level1end . $nav->navi_level2end . '<li',
		'</li>' . $nav->navi_level1end . $nav->navi_level2end . $nav->navi_level3end,
		'</li>' . $nav->navi_level1end . $nav->navi_level2end,
		'</li>' . $nav->navi_level2end . $nav->navi_level3end,
	);

	$replace = array (
		'',
		'',
		'',
		$nav->navi_level2begin . '<li',
		$nav->navi_level3begin . '<li',
		'</li>' . $nav->navi_level1end . '</li><li',
		'</li>' . $nav->navi_level2end . '</li><li',
		'</li>' . $nav->navi_level1end . '</li>' . $nav->navi_level2end . '</li><li',
		'</li>' . $nav->navi_level1end . '</li>' . $nav->navi_level2end . '</li>' . $nav->navi_level3end,
		'</li>' . $nav->navi_level1end . '</li>' . $nav->navi_level2end,
		'</li>' . $nav->navi_level2end . '</li>' . $nav->navi_level3end,
	);
*/	
	//$END = str_replace($search, $replace, $END);






	$navigations[$navigation_id] = $END;

	echo $END;

}

/**
 * Рекурсивная функция для формирования меню навигации
 *
 * @param string $navi
 * @param int $ebenen
 * @param string $way
 * @param int $rub
 * @param array $nav_items
 * @param string $row_ul
 * @param int $parent
 */
function printNavi(&$navi, &$ebenen, &$way, &$rub, &$nav_items, &$row_ul, $parent = 0)
{
	
	//print_r($parent);
	
	
	
	//$ebene = $nav_items[$parent][0]['navi_item_level'];
	$array = $nav_items[$parent];
	$array = array_shift($array);
	$ebene = $array['navi_item_level'];
	
//	array_shift(
	
	//print_r($navi);
//print_r($ebene);
	switch ($ebene)
	{
		case 1 : $navi .= $row_ul->navi_level1begin;  break;
		case 2 : $navi .= $row_ul->navi_level2begin;  break;
		case 3 : $navi .= $row_ul->navi_level3begin;  break;
	}
	
	$inter = '';


	foreach ($nav_items[$parent] as $row)
	{
		//print_r($way);
//		$aktiv = (in_array($row['Id'], $way) || strpos($row['navi_item_link'], 'index.php?' . $_SERVER['QUERY_STRING']) !== false) ? 'aktiv' : 'inaktiv';
		//if($row['parent_id'] != '0')$row['parent_name'] = $row['title'];
		
		//print_r($way);
		
		
		@$aktiv = (in_array($row['Id'], $way) || $_SERVER['REQUEST_URI'] == $row['navi_item_link']) ? 'aktiv' : 'inaktiv';
		@$akt = str_replace('[tag:linkname]', $row['title'], $ebenen[$ebene][$aktiv]);
		@$akt = str_replace('[tag:linkid]', $row['Id'], $akt);
		
		@$img = explode(".", $row['navi_item_Img']);
		@$row['Img_act'] = $img[0]."_act.".$img[1];
		
		//$parents = intval($row["parent_id"]);
		//print_r($row['Id']);
		@$row['parent_name'] = $nav_items[0][$parent]['title'];
		@$row['parent_document_alias'] = $nav_items[0][$parent]['document_alias'];
		@$row['parent_link'] = ((strpos($nav_items[0][$parent]['navi_item_link'], 'module=') === false && start_with('index.php?', $nav_items[0][$parent]['navi_item_link'])) ? $nav_items[0][$parent]['navi_item_link']. "&amp;doc=" . (empty($row['parent_document_alias']) ? prepare_url($row['parent_name']) : $row['parent_document_alias']) : $nav_items[0][$parent]['navi_item_link']);
		@$row['parent_name'] = ($row['parent_name']) ? "<h2><a href='".$row['parent_link']."'>".$row['parent_name']."</a></h2>" : "";
		
		
		
		
		
		@$akt = str_replace('[tag:desc]', stripslashes($row['navi_item_desc']), $akt);
		@$akt = str_replace('[tag:img]', stripslashes($row['navi_item_Img']), $akt);
		@$akt = str_replace('[tag:img_act]', stripslashes($row['Img_act']), $akt);
		@$akt = str_replace('[tag:img_id]', stripslashes($row['navi_item_Img_id']), $akt);

//print_r($row);

		if (strpos($row['navi_item_link'], 'module=') === false && start_with('index.php?', $row['navi_item_link']))
		{
				$akt = str_replace('[tag:link]', $row['navi_item_link'] . "&amp;doc=" . 
				(empty($row['document_alias']) ? prepare_url($row['title']) : $row['document_alias']), $akt);
		}
		else
		{	
#########################################
#########################################
#########для реврайтов мудулей###########		
			//if((strpos($row['navi_item_link'], 'gal-') !== false)){// если это галлерея
			//	//$akt = str_replace('[tag:link]', $row['navi_item_link'], $akt);
			//	$akt = str_replace('[tag:link]', $row['navi_item_link'] . "&amp;doc=" . $row['document_alias'], $akt);
			//}elseif((strpos($row['navi_item_link'], 'rub-') !== false)){ // если это рубрика
			//	//$akt = str_replace('[tag:link]', $row['navi_item_link'], $akt);
			//	$akt = str_replace('[tag:link]', $row['navi_item_link'] . "&amp;doc=" . $row['document_alias'], $akt);
#########################################
#########################################				
			//}else{
				$akt = str_replace('[tag:link]', $row['navi_item_link'], $akt);
				if (start_with('www.', $row['navi_item_link'])) $akt = str_replace('www.', 'http://www.', $akt);
			//}
		}
		
		@$akt = str_replace('[tag:submenu]', '[tag:submenu:'.$row['Id'].']', $akt);
		
		//print_r($row['Id']);
		
		
		

		$navi .= str_replace('[tag:target]', $row['navi_item_target'], $akt);
//		$akt = str_replace('[tag:target]', $row['navi_item_target'], $akt);
//		$navi .= rewrite_link($akt);


		
		if (isset($nav_items[$row['Id']]))
		{
			if($row_ul->id == 999){
				$submenu[] = $row['Id'];
			}else{
				printNavi($navi, $ebenen, $way, $rub, $nav_items, $row_ul, $row['Id']);
			}
		}
		
		
	}
		
//	print_r();
		
	$navi = str_replace('[tag:linkname]', $row['parent_name'], $navi);	
		
	switch ($ebene)
	{
		case 1 : $navi .= $row_ul->navi_level1end;  break;
		case 2 : $navi .= $row_ul->navi_level2end;  break;
		case 3 : $navi .= $row_ul->navi_level3end;  break;
	}

	//print_r($submenu);
	

if(!empty($submenu) && $row_ul->id == 999){
	foreach ($submenu as $id){
	//print_r('[tag:submenu_'.$id.']');
	
		$navi2 = '';
		printNavi($navi2, $ebenen, $way, $rub, $nav_items, $row_ul, $id);
		@$navi = str_replace('[tag:submenu:'.$id.']', $navi2, $navi);
	}
	
	
	
}


	//print_r($nav_items);


//'<div class="main_link"><a href="[tag:target]" target="[tag:target]" class="">name</a></div>'.


//	
//	if(!empty($submenu) && $row_ul->id == 2){
//		foreach ($submenu as $id){
//			printNavi($navi, $ebenen, $way, $rub, $nav_items, $row_ul, $id);
//		}
//	}

	
}

?>